<?php
namespace app\ebcms\controller;
class Group extends \app\ebcms\controller\Common
{
    
    public function index()
    {
        if (request()->isGet()) {
            return $this->fetch();
        }
    }

    public function add()
    {
        if (request()->isGet()) {
            return \ebcms\Form::fetch();
        } elseif (request()->isPost()) {
            $obj = new \app\ebcms\model\Group();
            if (false !== $obj ->validate('Group.add')->save(input())) {
                $this -> success('操作成功！');
            }else{
                $this -> error($obj -> getError());
            }
        }
    }

    public function edit($id)
    {
        if (request()->isGet()) {
            $obj = \app\ebcms\model\Group::get(input('id'));
            return \ebcms\Form::fetch($obj);
        } elseif (request()->isPost()) {
            $obj = \app\ebcms\model\Group::get(input('id'));
            if (false !== $obj -> validate('Group.edit') -> isUpdate(true) -> save(input())) {
                $this -> success('操作成功！');
            }else{
                $this -> error($obj -> getError());
            }
        }
    }

    public function resort(){
        \app\ebcms\model\Group::where('id',input('id')) -> setField('sort',input('value'));
        $this -> success('操作成功！');
    }

    public function status()
    {
        \app\ebcms\model\Group::where(['id'=>['in',input('ids')]]) -> setField('status',input('value')?1:0);
        $this -> success('操作成功！');
    }

    public function delete()
    {
        $items = \app\ebcms\model\Group::where(['id'=>['in',input('ids')]]) -> select();
        foreach ($items as $key => $obj) {
            $obj -> manager() -> detach(true);
            $obj -> delete();
        }
        $this -> success('删除成功！');
    }

    public function rule()
    {
        if (request()->isGet()) {
            return \ebcms\Form::fetch();
        } elseif (request()->isPost()) {
            $id = input('id');
            $rule_ids = input('rule_ids/a',[]);
            if (false !== \think\Db::name('auth_group')->where(array('id' => array('eq', $id)))->setField('rules', implode(',', $rule_ids))) {
                $this->success('权限分配成功！');
            } else {
                $this->error(\think\Db::name('auth_group')->getDbError());
            }
            $this->success('权限分配成功！');
        }
    }

    // 功能菜单分配
    public function menu()
    {
        if (request()->isGet()) {
            return \ebcms\Form::fetch();
        } elseif (request()->isPost()) {
            $id = input('id', 0, 'intval');
            $menu_ids = input('menu_ids/a',[]);
            if (false !== \think\Db::name('auth_group')->where(array('id' => array('eq', $id)))->setField('menus', implode(',', $menu_ids))) {
                $this->success('功能分配成功！');
            } else {
                $this->error(\think\Db::name('auth_group')->getDbError());
            }
        }
    }
}